package io.renren.utils;

import com.alibaba.fastjson.JSONObject;
import io.renren.config.APPParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Map;

/**
 * Created by Yorke on 2017/2/28.
 *
 * 测试静态方法用，使用注入配置参数
 */
@Component
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    @Autowired
    private APPParameter appParameter;

    private static FileUtils fileUtils;


    @PostConstruct
    public void init() {
        fileUtils = this;
        fileUtils.appParameter = this.appParameter;
    }

    public static void wirteFileByFreemarker(String outfilepath, String outfilename, String templatepath, Map map) {

        logger.info("wirteFileByFreemarker reportParameter: {}", JSONObject.toJSONString(fileUtils.appParameter));


        logger.info("wirteFileByFreemarker outfilepath: {}", outfilepath);
        try {
            FreeMarkerUtils.generateByTemplate(templatepath, map, fileUtils.appParameter.getAppRootPath() + File.separator + outfilepath, outfilename);
        } catch (Exception e) {
            logger.error("wirteFileByFreemarker error!", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * 读取txt文件
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String  readTxt(String filePath) throws Exception{
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(s+"&");
            }
            br.close();
        }catch(Exception e){
            throw  new Exception("读取文件错误");
        }
        return result.toString();

    }


}
